package tools

import (
	"bytes"
	"errors"
	"fmt"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"net/http"
	"runtime"
	"time"
)

func window(bg int, str string) string {
	return fmt.Sprintf("\x1b[0;%dm%s\x1b[0m", bg, str)
}

func linux(bg int, str string) string {
	return fmt.Sprintf("\033[%d;48m%s\033[0m", bg, str)
}

func machine(bg int, str string) string {
	switch runtime.GOOS {
	case "linux":
		return linux(bg, str)
	case "windows":
		return window(bg, str)
	}
	panic("无法识别")
	return ""
}

func DrawQrcode(uri string) (errs error) {
	defer func() {
		if err := recover(); err != nil {
			errs = errors.New(fmt.Sprintf("无法识别系统，建议直接读取图片%s", err))
		}
	}()
	body, _, err := Get(uri, nil, nil, &http.Client{Timeout: 120 * time.Second})
	if err != nil {
		return err
	}
	images := bytes.NewReader(body)
	// 解码图片
	img, _, err := image.Decode(images)
	if err != nil {
		return errors.New(fmt.Sprintf("解码图片失败：%v", err))
	}

	// 获取图片的宽和高
	bounds := img.Bounds()
	// 遍历图片的每一个像素
	for y := bounds.Min.Y; y <= bounds.Max.Y; y += 10 { //bounds.Min.Y bounds.Max.Y
		content := ""
		status := false

		for x := bounds.Min.X; x <= bounds.Max.X; x += 10 {
			// 获取像素的RGBA颜色值
			r, g, b, _ := img.At(x, y).RGBA()

			// 如果需要，可以将RGBA值转换为更常用的格式，如uint8
			r8 := uint8(r >> 8)
			g8 := uint8(g >> 8)
			b8 := uint8(b >> 8)
			//a8 := uint8(a >> 8)

			if r8 >= 200 && g8 >= 200 && b8 >= 200 {
				status = true
				content = content + machine(47, "  ")
			}
			if status && r8 < 200 && g8 < 200 && b8 < 200 {
				content = content + machine(40, "  ")
			}
		}
		if status {
			fmt.Println(content)
		}
	}
	fmt.Printf("二维码网址：%v\n", uri)
	return nil
}
